#!/bin/bash
trap "rm -rf ${bak_dir}/${bak_filename}/" SIGHUP SIGINT SIGTERM
source ../source/common/functions.sh
source ../source/common/bussinessfun.sh
#set Var
NAME=`basename $0`
dir=`pwd`
#配置文件
conf=DIRCONFIG.ini
#读取配置文件中，备份到磁盘的具体位置
bak_dir=`readIni conf.ini backup backupdir`
#获取本地ip
ip=`GetLocalIp`
#获取包名
packagename=`basename ${dir%/backup}`
#获取系统名
sys=`echo ${packagename}|cut -d "-" -f2`
#设置备份文件的目录名称格式
bak_filename=`date +%F`_"$ip"_"$sys"_"backup"


#备份
function Backup() {
#讲传入的文件，进行压缩，并移动到变量所设置的目录中去
	local back_file=$1
	local param=$2
	
	mkdir -p ${bak_dir}/${bak_filename}
	tar -Pzcvf $1.tgz $1 $2
	mv $1.tgz ${bak_dir}/${bak_filename}
	cd ${bak_dir}
	tar Pzcvf ${bak_filename}.tgz ${bak_filename}
	ClearOldBackup
}
function ClearOldBackup(){	
	#clear old backup
	local bak_all=`ls $bak_dir | grep .tgz`
	if [ X"${bak_all}" != X ]
	then
		cd $bak_dir
		ls -lt *.tgz|awk 'BEGIN{ FS="[ ]+"};{print $9}'|sed '1,7d'|xargs rm -rf
	fi
}
function BackupStep() {
	IFS=$'\n'
	if [ -f $dir/${conf} ]
	then
		for xpath in `cat $dir/${conf}|grep -v ^#`
		do
			if [ X"${xpath}" = X ]
			then
				yaoecho hr "Backup DIRCONFIG file have no content ! Please check it !"
				EchoErr ${LINENO}
				exit 1
			fi
			local num=`echo ${xpath%;}|cut -d "=" -f2|grep -o ";"|wc -l`
			local bakfile=`echo ${xpath}|cut -d "=" -f1`
			local bakfiledir=`echo ${xpath}|cut -d "=" -f2|cut -d ";" -f1`
			for((i=2;i<=$((${num} + 1));i++))
			do
				local excludefile=`echo ${xpath%;}|cut -d"=" -f2|awk -F ";" '{print $'$i'}'`
				local excludefiles="${excludefiles} --exclude=${excludefile}"
			done
			if ([ X"${bakfile}" = X ] || [ X"${bakfiledir}" = X ] )
			then
				yaoecho hr "DIRCONFIG file  format error ! Please check it !"
				EchoErr ${LINENO}
				exit 1
			fi
			if [ -d ${bakfiledir} ]
			then
				cd ${bakfiledir}
				[ X`ls|grep ${bakfile}` = X ] || eval Backup "${bakfile}" "${excludefiles}"
			else
				echo	
			fi
			#[[ X"$excludefiles" = X ]]
		done
		rm -rf ${bak_filename}
	else
		yaoecho hr "backup DIRCONFIG not exist,please check it"
		EchoErr ${LINENO}
	fi
}

#执行备份函数
BackupStep


